﻿package cn.poco.service.impl;
import java.io.InputStream;
import java.util.List;

import android.content.Context;
import android.util.Log;
import cn.poco.bean.City;
import cn.poco.dao.CacheDbService;
import cn.poco.service.ICity;
import cn.poco.util.UrlConnectionUtil;
import cn.poco.util.xmlparse.CityXmlparse;
import cn.poco.util.xmlparse.GPSCityXmlparse;


public class CityImpl implements ICity {


	//List<City> switchCity(Context context)方法：传入上下文（Activity）,返回装载城市对象的集合
	@Override
	public List<City> switchCity(Context context) throws Exception{
		
		// 获得输入流对象     <---------调用连接工具类 getRequest方法
		InputStream inSteam = UrlConnectionUtil.getRequest(CITY_URL);
		
		// 集合citys <--------调用解析XML类
		List<City> citys = CityXmlparse.getXml(inSteam);
		
		//将城市数据写入数据库
		CacheDbService db = new CacheDbService(context);
		db.saveCity(citys);
		
		//返回城市对象集合
		return citys;
	}
	
	
	
	//通过经纬度(lat,lon)获得城市，抛异常
	@Override
	public City switchCitybyGps(double lat, double lon) throws Exception {
		
		/**
		 *       CITY_GPS_URL是接口ICity的成员变量
		         final static String CITY_GPS_URL 
		                     = "http://img-m.poco.cn/mypoco/mtmpfile/food_iphone/getCityByGPS.php?lat=#a&long=#b";
		                 */
		//代入经纬度值    替代  #a  #b
		String url = CITY_GPS_URL.replace("#a", String.valueOf(lat));
		       url  =url.replace("#b", String.valueOf(lon));
		       
		Log.i(TAG, url);
		
		//获得输入流对象
		InputStream inSteam = UrlConnectionUtil.getRequest(url);
		City city  = GPSCityXmlparse.getXml(inSteam);
		return city;
	}

	


}
